<script setup>
import {
  forgetPasswordAPI,
  getUserPhoneAPI,
  validatePhoneAPI
} from '@/api/forget'
import { getCodeAPI } from '@/api/login'
import { ArrowLeft, Cellphone, Lock, User } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const stepActive = ref(0)

// 返回登录
const backLogin = () => {
  router.replace('/login')
}
const tip = ref('') // 服务器返回信息
const nextSetp = async () => {
  // 完成
  if (stepActive.value === 4) {
    return router.replace('/login')
  }
  await forgetRef.value?.validate()
  // 填写用户名
  if (stepActive.value === 0) {
    const { data: res } = await getUserPhoneAPI({
      userName: forgetData.value.userName
    })
    if (res.status !== 200) {
      return (tip.value = res.message)
    }
    if (res.data.role !== 1) {
      tip.value = '用户为管理员或教师用户，请勿在学生端修改密码'
      return
    }
    forgetData.value.phone = res.data.phone
    stepActive.value = ++stepActive.value
    tip.value = ''
    return
  }

  // 手机验证
  if (stepActive.value === 1) {
    const { data: res } = await validatePhoneAPI({
      phone: forgetData.value.phone,
      code: forgetData.value.code
    })
    if (res.status !== 200) {
      return (tip.value = res.message)
    }
    stepActive.value = ++stepActive.value
    tip.value = ''
    return
  }

  // 填写密码
  if (stepActive.value === 2) {
    const { data: res } = await await forgetPasswordAPI({
      userName: forgetData.value.userName,
      phone: forgetData.value.phone,
      newPassword: forgetData.value.confirmPassword
    })
    if (res.status !== 200) {
      return (tip.value = res.message)
    }
    stepActive.value += 2
    tip.value = ''
    return
  }
}
const forgetRef = ref()
const forgetData = ref({
  userName: '',
  phone: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const checkPassword = (rule, value, callback) => {
  const regex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/
  if (value === '') {
    callback(new Error('请输入密码'))
  }
  if (!regex.test(value)) {
    callback(new Error('请输入6位包含字母、数字组合的密码'))
  }
  if (forgetData.value.confirmPassword !== '') {
    if (forgetData.value.confirmPassword === value) {
      callback()
    }
    forgetRef.value?.validateField('confirmPassword')
  }
  callback()
}
const checkConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  }
  if (value === forgetData.value.newPassword) {
    callback()
  } else {
    callback(new Error('新旧密码不一致'))
  }
}
const forgetRules = {
  userName: [{ required: true, message: '请输入用户名' }],
  phone: [{ required: true, message: '请输入手机号' }],
  code: [{ required: true, message: '请输入验证码' }],
  newPassword: [
    {
      required: true,
      validator: checkPassword,
      trigger: 'change'
    }
  ],
  confirmPassword: [
    {
      required: true,
      validator: checkConfirmPassword,
      trigger: 'change'
    }
  ]
}

// 手机号验证 ---- stepActive === 1
const isPhoneDisabled = ref(true)
const isDisabled = ref(false)
// 获取验证码
const time = ref(60)
const getCode = async () => {
  await forgetRef.value?.validateField(['phone'])
  const { data: res } = await getCodeAPI(forgetData.value.phone)
  if (res.status === 200) {
    ElMessage.success(res.message)
    isDisabled.value = true
    const n = setInterval(() => {
      time.value--
      if (time.value === 0) {
        isDisabled.value = false
        time.value = 60
        clearInterval(n)
      }
    }, 1000)
  }
}
</script>

<template>
  <div class="forget-container">
    <el-card class="forget-box">
      <div class="forget-top">
        <el-icon class="forget-top-icon" size="30" @click="backLogin"
          ><ArrowLeft
        /></el-icon>
        <h1 class="forget-title">忘记密码</h1>
      </div>
      <div class="forget-content">
        <el-form
          ref="forgetRef"
          :model="forgetData"
          :rules="forgetRules"
          label-width="120px"
          v-if="stepActive !== 4"
        >
          <el-form-item label="用户名" prop="userName" v-if="stepActive === 0">
            <el-input
              :prefix-icon="User"
              v-model="forgetData.userName"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="phone"
            v-if="stepActive === 1"
            class="forget-phone-item"
            label="手机号"
          >
            <el-input
              style="width: 220px"
              v-model="forgetData.phone"
              :prefix-icon="Cellphone"
              placeholder="请输入手机号"
              :disabled="isPhoneDisabled"
            ></el-input>
            <el-button
              style="margin-left: 0.1rem"
              :disabled="isDisabled"
              @click="getCode"
              >{{ time < 60 ? time : '获取验证码' }}</el-button
            >
          </el-form-item>
          <el-form-item prop="code" label="验证码" v-if="stepActive === 1">
            <el-input
              style="width: 2.2rem"
              v-model="forgetData.code"
              :prefix-icon="Lock"
              placeholder="请输入验证码"
              maxLength="4"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="新密码"
            prop="newPassword"
            v-if="stepActive === 2"
          >
            <el-input
              v-model="forgetData.newPassword"
              placeholder="请输入新密码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="确认密码"
            prop="confirmPassword"
            v-if="stepActive === 2"
          >
            <el-input
              v-model="forgetData.confirmPassword"
              placeholder="请再次输入新密码"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-result
          style="min-width: 6rem"
          v-else
          icon="success"
          title="修改成功"
        />
      </div>
      <div class="forget-step-tip">
        <el-alert
          :title="tip"
          type="error"
          :closable="false"
          center
          v-show="tip !== ''"
        />
      </div>

      <div class="forget-step-box">
        <el-steps
          class="forget-step"
          :active="stepActive"
          finish-status="success"
          align-center
        >
          <el-step title="填写用户名" />
          <el-step title="手机号验证" />
          <el-step title="修改密码" />
          <el-step title="完成" />
        </el-steps>
        <el-button type="primary" @click="nextSetp">{{
          stepActive === 4 ? '完成' : '下一步'
        }}</el-button>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.forget-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  .forget-box {
    min-width: 8.92rem;
    min-height: 5.2rem;
    padding: 0.14rem 0.2rem;
    .forget-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .forget-top-icon {
        cursor: pointer;
        transition: all 0.2s;
        width: 0.3rem;
        height: 0.3rem;
        &:hover {
          color: #409aff;
        }
      }
      .forget-title {
        margin-bottom: 0.2rem;
        font-size: 0.32rem;
      }
    }

    .forget-content {
      min-height: calc(3.2rem - 0.8rem);
      display: flex;
      justify-content: space-between;
      align-items: center;
      .forget-phone-item {
        :deep(.el-form-item__content) {
          flex-wrap: nowrap;
        }
      }
    }
    .forget-step-tip {
      max-width: 6rem;
      margin-bottom: 0.4rem;
      min-height: 0.4rem;
      :deep(.el-alert__title) {
        font-size: 0.16rem;
        letter-spacing: 0.02rem;
        font-weight: 800;
      }
    }
    .forget-step-box {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      .forget-step {
        max-width: 6rem;
        flex: 4;
        :deep(.el-step__head) {
          display: flex;
          justify-content: center;
        }
      }
    }
  }
}
</style>
